package com.yang.news.job.jobhandler;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yang.convert.HotSearchConvert;
import com.yang.news.model.dto.HotSearchDetailDTO;
import com.yang.news.dao.entity.HotSearchRecord;
import com.yang.news.service.HotSearchRecordService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

import static com.yang.news.model.cache.HotSearchCache.CACHE_MAP;
import static com.yang.news.enums.HotSearchEnum.DOUYIN;

/**
 * @author Billyang
 * @date 2024/8/13 11:46
 */
@Slf4j
@Component
public class DouyinHotSearchJob {

    @Autowired
    private HotSearchRecordService hotSearchRecordService;

    @PostConstruct
    public void init(){
        try{
            hotSearch(null);
            log.info("初始化抖音数据成功");
        }catch (Exception e){
            log.error("初始化抖音数据异常",e);
        }
    }

    /**
     * 定时触发爬虫方法，1个小时执行一次
     */
    @XxlJob("douyinHotSearchJob")
    public ReturnT<String> hotSearch(String param) {
        try {
            log.info("开始爬取抖音热搜数据");
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/")
                    .method("GET", null) // 注意这里将RequestBody设置为null
                    .addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                    .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                    .addHeader("cache-control", "max-age=0")
                    .addHeader("priority", "u=0, i")
                    .addHeader("referer", "https://link.juejin.cn/")
                    .addHeader("sec-ch-ua", "\"Not)A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"127\", \"Chromium\";v=\"127\"")
                    .addHeader("sec-ch-ua-mobile", "?0")
                    .addHeader("sec-ch-ua-platform", "\"Windows\"")
                    .addHeader("sec-fetch-dest", "document")
                    .addHeader("sec-fetch-mode", "navigate")
                    .addHeader("sec-fetch-site", "cross-site")
                    .build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray array = jsonObject.getJSONArray("word_list");
            List<HotSearchRecord> hotSearchList = Lists.newArrayList();

            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                HotSearchRecord hotSearchRecord = HotSearchRecord.builder().hotSearchResource(DOUYIN.getCode()).build();
                hotSearchRecord.setHotSearchResource(DOUYIN.getCode());
                //设置文章标题
                hotSearchRecord.setHotSearchTitle(object.getString("word"));
                //设置抖音三方ID
                hotSearchRecord.setHotSearchId(getHashId(DOUYIN.getCode() + hotSearchRecord.getHotSearchTitle()));
                //设置文章连接
                hotSearchRecord.setHotSearchUrl(
                        "https://www.douyin.com/search/" + hotSearchRecord.getHotSearchTitle() + "?type=general");
                //设置热搜热度
                hotSearchRecord.setHotSearchHeat(object.getString("hot_value"));
                //按顺序排名
                hotSearchRecord.setHotSearchOrder(i + 1);
                hotSearchList.add(hotSearchRecord);
            }

            if (CollectionUtils.isEmpty(hotSearchList)) {
                return ReturnT.SUCCESS;
            }
            //数据加到缓存中
            CACHE_MAP.put(DOUYIN.getCode(), HotSearchDetailDTO.builder()
                    //热搜数据
                    .hotSearchDTOList(
                            hotSearchList.stream().map(HotSearchConvert::toDTOWhenQuery).collect(Collectors.toList()))
                    //更新时间
                    .updateTime(Calendar.getInstance().getTime()).build());
            hotSearchRecordService.batchSave(hotSearchList);
            log.info("抖音热搜数据爬取成功");
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            log.error("获取抖音数据异常",e);
        }
        return ReturnT.FAIL;
    }

    /**
     * 根据文章标题获取一个唯一ID
     *
     * @param title 文章标题
     * @return 唯一ID
     */
    public static String getHashId(String title) {
        long seed = title.hashCode();
        Random rnd = new Random(seed);
        return new UUID(rnd.nextLong(), rnd.nextLong()).toString();
    }
}
